package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * 体检套餐
 */

@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Reference
    private SetmealService setmealService;

    // JedisPool实例
    @Autowired
    private JedisPool jedisPool ;

    //获取所有套餐信息
    @RequestMapping("/getSetmeal")
    public Result getSetmeal(){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String setmealListJson = jedis.get("setmealList");
            if (setmealListJson != null && !"".equals(setmealListJson)) {
                // 从Redis中获取套餐信息
                // 这里假设setmealListJson是一个JSON字符串，需要反序列化为List<Setmeal>
                List<Setmeal> list = JSON.parseArray(setmealListJson, Setmeal.class);
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, list);
            } else {
                // 从数据库中查询套餐信息
                List<Setmeal> list = setmealService.findAll();
                // 将查询结果存入Redis
                jedis.setex("setmealList", 60 * 60 * 24 * 7 , JSON.toJSONString(list));
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        } finally {
            // 关闭Jedis连接
            if (jedis != null) {
                jedis.close(); // 确保连接归还给连接池
            }
        }
    }

    //根据套餐id查询套餐详情，包含（套餐基本信息、套餐关联的检查组、检查组关联的检查项）
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Setmeal setmeal = setmealService.findById(id);
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS,setmeal);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }
}